/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
  // let saleValue = [0], buyValue = [-prices[0]];
  // for(let i = 1; i < prices.length; i++) {
  //   saleValue[i] = Math.max(buyValue[i - 1] + prices[i], saleValue[i - 1]);
  //   buyValue[i] = Math.max(buyValue[i - 1], -prices[i]);

  // }
  // return saleValue[prices.length - 1];
  let saleValue = 0, buyValue = -prices[0];
  for(let i = 1; i < prices.length; i++) {
    saleValue = Math.max(buyValue + prices[i], saleValue);
    buyValue = Math.max(buyValue, -prices[i]);
  }
  return saleValue;
};

let prices = [7,1,5,3,6,4];
console.log(maxProfit(prices));
prices = [7,6,4,3,1];
console.log(maxProfit(prices));
